<?php
class CartController extends Zend_Controller_Action {

	public function indexAction() {
	    $this->view->headTitle()->append('корзина');
	    $cartMapper = new Model_Cart_Mapper();
	    if(Zend_Auth::getInstance()->hasIdentity()){
            $cart = $cartMapper->loadByUserId(Zend_Auth::getInstance()->getIdentity()->id);
        } else {
            $cart = $cartMapper->loadByUserId();
        } 
        $this->view->cart = $cart;
	} 
	
	public function addAction()
	{
		$productMapper = new Model_Product_Mapper();
		$data = $productMapper->load((int) $this->_getParam('id'))->toArray();
        $cartMapper = new Model_Cart_Mapper();
        $cartProduct = new Model_Product_Cart($data);
        if(Zend_Auth::getInstance()->hasIdentity()){
            $cart = $cartMapper->loadByUserId(Zend_Auth::getInstance()->getIdentity()->id);
        } else {
            $cart = $cartMapper->loadByUserId();
        }
        $cart->addProduct($cartProduct);
        $cartMapper->save($cart);
        $this->_redirect($_SERVER['HTTP_REFERER']);
	}
	
	public function deleteAction()
	{
	    $productMapper = new Model_Product_Mapper();
        $data = $productMapper->load((int) $this->_getParam('id'))->toArray();
        $cartMapper = new Model_Cart_Mapper();
        $cartProduct = new Model_Product_Cart($data);
        if(Zend_Auth::getInstance()->hasIdentity()){
            $cart = $cartMapper->loadByUserId(Zend_Auth::getInstance()->getIdentity()->id);
        } else {
            $cart = $cartMapper->loadByUserId();
        }
        $cart->removeProduct($cartProduct);
        Zend_Debug::dump($cart);
        $cartMapper->save($cart);
        $this->_redirect($_SERVER['HTTP_REFERER']);
	}
}

